<template>
  <view :style="{ opacity: curPage === 'map' ? '0' : '1'}">
    <uni-nav-bar :title="fillAll.code" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
    <view class="package">
      <view class="space-between">
        <view>加注机别名</view>
        <view>{{fillAll.code}}({{fillAll.id}})</view>
      </view>
      <view class="space-between top">
        <view>串号</view>
        <view>{{fillAll.imsi}}</view>
      </view>
      <view class="space-between top">
        <view>存量</view>
        <view>{{fillAll.count}}公斤</view>
      </view>
    </view>
    <view class="package" style="padding:0px 25rpx;">
      <view class="space-between types">
        <view>是否开放</view>
        <uni-data-checkbox v-model="state1" :localdata="type1" @change="changes($event, '1')"></uni-data-checkbox>
      </view>
      <view class="space-between types">
        <view>加注机类型</view>
        <uni-data-checkbox v-model="state2" :localdata="type2" @change="changes($event, '2')"></uni-data-checkbox>
      </view>
      <view class="space-between types">
        <view>加注机状态</view>
        <uni-data-checkbox v-model="state3" :localdata="type3" @change="changes($event, '3')"></uni-data-checkbox>
      </view>
      <view class="space-between types">
        <view>环境</view>
        <uni-data-checkbox v-model="state4" :localdata="type4" @change="changes($event, '4')"></uni-data-checkbox>
      </view>
    </view>
    <view class="package" style="padding:0px 25rpx;">
      <view class="space-between types">
        <view>加注机别名</view>
        <input type="text" placeholder="请输入加注机别名" v-model="fillName">
      </view>
     <!-- <view class="space-between types">
        <view>今日单价</view>
        <input type="text" placeholder="请输入今日单价" v-model="fillName">
      </view> -->
      <view class="space-between types">
        <view>绑定号码</view>
        <input type="text" placeholder="请输入加注机的绑定号码" v-model="number">
      </view>
      <view class="space-between types" @click="chooseLocation()">
        <view>地址</view>
        <view style="width: 75%;text-align: right;">{{locName?locName:fillAll.address}}</view>
      </view>
    </view>
    <view class="package">
      <view>图片</view>
      <view class="center laint">
        <image v-for="item in fillAll.images" :src="item.image" mode=""></image>
      </view>
      <!-- <mk-upload :imgList="imgList" @onDelete="onDelete" @onChoose="onChoose" /> -->
    </view>
  </view>
  <view class="add" @click="submit()">确定</view>
  <view style="width:100%;height:1px;"></view>
  <!-- 选择地址列表 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import { navBack, navTo } from '@/utils/navigator';
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  import Lotlats from '@c/team/Lotlat.vue';
  // import mkUpload from "@c/mk-upload/mk-upload.vue"
  import { onLoad } from '@dcloudio/uni-app';
  import { ref, Ref } from 'vue';
  import { showLoading, errorToast, successToast } from '@/utils/prompt';
  import { getFill } from '@/gql/administrator';
  import { toPublish } from '@mqtt';
  const state1 = ref(0)
  const type1 = [{ text: '开放', value: '1', disable: true }, { text: '专营', value: '0', disable: true }]
  const state2 = ref(0)
  const type2 = [{ text: '移动', value: 0, disable: true }, { text: '固定', value: 1, disable: true }]
  const state3 = ref(0)
  const type3 = [{ text: '启用', value: '1', disable: true }, { text: '未启用', value: '0', disable: true }]
  const state4 = ref(0)
  const type4 = [{ text: '正式环境', value: 'formal', disable: true }, { text: '测试环境', value: 'test', disable: true }]
  // data
  const curPage : Ref<'form' | 'map'> = ref('form');
  const longitude = ref()
  const latitude = ref()
  const mapURI = ref('');
  const locName = ref('')
  // 修改信息
  const FillID = ref()
  const fillName = ref('')
  const number = ref('')
  const fillAll = ref({})
  // 上传图片
  // const imgList = ref([])
  onLoad((pearm) => {
    FillID.value = pearm.id
    init()
  })
  function init() {
    showLoading('正在加载');
    const payload = {
      query: getFill,
      variables: {
        fill_id: Number(FillID.value)
      },
    };
    toPublish('ql/control/getFill', payload, (obj : any) => {
      uni.hideLoading();
      const { getFill } = obj.data;
      fillAll.value = getFill;
      fillName.value = getFill.code
      number.value = getFill.fill_code
      state1.value = getFill.is_open
      state2.value = getFill.type === 'move' ? 0 : 1
      state3.value = getFill.status
      state4.value = getFill.env
      locName.value = getFill.address
    });
  }
  // function onChoose(e : any) {
  //   console.log(JSON.stringify(e))
  //   imgList.value.push(e.tempFilePaths[0])
  //   uni.uploadFile({
  //     url: '', 
  //     filePath: e.tempFilePaths[0],
  //     name: 'file',
  //     formData: {
  //       'user': 'test'  // 上传附带参数
  //     },
  //     success: (uploadFileRes) => {
  //       // 根据接口具体返回格式   赋值具体对应url
  //       console.log(uploadFileRes.data);
  //     }
  //   });
  // }
  // 删除图片
  // function onDelete(index : number) {
  //   imgList.value.splice(index, 1);
  // }
  /**
   * 获取当前城市信息
   * @param  lat 当前位置的纬度
   * @param  lot 当前位置的经度
   */
  function position(lat : number, lot : number) {
    longitude.value = lot;
    latitude.value = lat;
    getPositionByLonLats(lot, lat)
  }
  function getPositionByLonLats(lng : number, lat : number) {
    AMapLoader.load({
      key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
    })
      .then(AMap => {
        const lnglat = [lng, lat]
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, function (status : any, result : any) {
          if (status === 'complete' && result.regeocode) {
            locName.value = fillAll.value.address ? fillAll.value.address : result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
      })
  }
  /**
   * 跳转到地址列表 选择位置信息
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        console.log(JSON.stringify(loc) + '*****')
        curPage.value = 'form';
        longitude.value = loc.latlng.lng;
        latitude.value = loc.latlng.lat;
        locName.value = loc.poiname
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  function submit() {
    var payload = { fill_id: Number(FillID.value) }
    if (fillAll.value.code != fillName.value) {
      payload.code = fillName.value
    }
    if (fillAll.value.address != locName.value) {
      payload.latitude = latitude.value
      payload.longitude = longitude.value
      payload.address = locName.value
    }
    if (fillAll.value.fill_code != number.value) {
      payload.fill_code = number.value
    }
    showLoading()
    toPublish('control/editFill', payload, (obj : any) => {
      uni.hideLoading();
      const { code, msg } = obj;
      if (code === 1) {
        successToast(msg)
        navBack()
      } else {
        errorToast(msg)
      }
    });
  }
  function changes(e : any, nums : string) {
    console.log(e.detail.data, nums, state1.value)
    switch (nums) {
      case '1':
        break;
      case '2':
        break;
    }
  }
</script>

<style scoped lang="less">
  .types:nth-last-child(1) {
    border-bottom: 0px;
  }

  .types {
    width: 100%;
    padding: 25rpx 0px;
    box-sizing: border-box;
    border-bottom: 1px solid #eee;
  }

  .top {
    margin-top: 15rpx;
  }

  .add {
    width: 480rpx;
    height: 100rpx;
    background: linear-gradient(-10deg, #2C96F9, #1B91FF);
    border-radius: 5px;
    text-align: center;
    line-height: 100rpx;
    color: #fff;
    margin: 40rpx auto 20rpx;
    font-size: 32rpx;
  }

  .laint {
    flex-wrap: wrap;

    image {
      width: 128rpx;
      height: 97rpx;
      background: #E9EDF3;
      border-radius: 5px;
      margin: 15rpx 15rpx 0px 0px;
    }
  }

  input {
    text-align: right;
  }
</style>
<style>
  .space-between>>>.uni-data-checklist .checklist-group {
    justify-content: flex-end;
  }

  .space-between>>>.uni-data-checklist .checklist-group .checklist-box .checklist-content .checklist-text {
    color: #333 !important;
  }

  .space-between>>>.uni-data-checklist .checklist-group .checklist-box:nth-last-child(1) {
    margin-right: 0px;
  }
</style>